<?php

namespace backend\services\captcha;

use backend\extensions\ApiBaseService;
use yii\captcha\CaptchaAction;

/**
 * Desc 验证码服务类
 * @author HUI
 */
class CaptchaService extends ApiBaseService {
    
    const CAPTCHA_KEY = 'capcha_';
    
    //初始化
    const CONFIG = [
        'maxLength' => 4, //最大显示个数
        'minLength' => 4, //最少显示个数
        'backColor' => 0xFFFFFF, //背景颜色
        'foreColor' => 0x84C1FF, //字体颜色
        'width' => 100,
        'height' => 38,
        'padding' => 0,
        'offset' => 4,
    ];

    /**
     * 获取验证码
     * **/
   public static function getCaptcha($uuid) {
        $captcha = new CaptchaAction(\Yii::$app->controller->id, \Yii::$app->controller, self::CONFIG);
        $base64 = 'data:image/png;base64,' . base64_encode($captcha->run());
        \Yii::$app->cache->set(self::CAPTCHA_KEY . $uuid, $captcha->getVerifyCode(), 60 * 10);
        //重写run里边的响应格式
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $base64;
    }
    
    /**
     * 验证码校验
     * * */
    public static function validateCode($params) {
        $code = \Yii::$app->cache->get(self::CAPTCHA_KEY . $params['uuid']);
        if (empty($code)) {
            return self::jsonError('验证码已过期，请重新操作');
        }
        if (strtolower($code) != strtolower($params['code'])) {
            return self::jsonError('验证码不对，请重新操作');
        }
        return self::jsonSuccess();
    }
}
